<template>
  <div id="login_box">
    <!-- <div class="logo"> -->
      <!-- <img src="/static/img/top_logo.d96327d.png" alt="康来生物"> -->
    <!-- </div> -->
    <div class="login_form">
      <el-form
        :model="loginInfo"
        autoComplete="on"
        status-icon
        :rules="rules"
        ref="loginInfo"
      >
        <el-form-item style="margin-bottom: 0;">
          <div class="user-type">
            <img src="../assets/img/icon_userrole.png" />
            <el-radio-group v-model="loginInfo.userRole">
              <el-radio :label="1" :key="1">管理员</el-radio>
              <el-radio :label="3" :key="3">商户</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item>
          <el-input
              size="medium"
            type="text"
            placeholder="请输入用户名"
            v-model="loginInfo.userName"
          >
              <img slot="prefix" src="../assets/img/icon_username.png" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input
              size="medium"
            type="password"
            placeholder="请输入密码"
              show-password
            v-model="loginInfo.password"
          >
              <img  slot="prefix" src="../assets/img/icon_password.png" />
          </el-input>
        </el-form-item>

        <el-form-item v-if="showTenant">
          <el-select
              size="medium"
            class="tenant-select"
            v-model="loginInfo.tenantId"
            placeholder="请选择租户"
            clearable
            filterable
          >
              <img slot="prefix" src="../assets/img/icon_tenant.png" />
            <el-option
              v-for="item in tenantList"
              :value="item.value"
              :label="item.name"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-top: 40px">
          <el-button @click="submitForm" type="primary" class="login_btn"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import MD5 from "js-md5";
import { mapActions } from "vuex";
import LoginApi from "@/api/system/login";
import {setCookies,getCookies,removeCookies,setStorage} from "@/utils/auth";
import * as stn from "@/constants/storeName";
import TenantApi from "@/api/system/tenant";
export default {
  data() {
    return {
      showTenant: false,
      tenantList: [],
      loginInfo: {
        userName: "",
        password: "",
        userRole: 1,
        codeValidate: "",
        isChecked: false,
        tenantId: ""
      },
      passwordType: "password",
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        userRole: [{ required: true, message: "请选择角色", trigger: "change" }]
      }
    };
  },
  methods: {
    ...mapActions({
      setToken: "setToken"
    }),
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode === 13) {
        this.submitForm();
      }
    },
    savePwd() {
      if (this.loginInfo.isChecked) {
        let md5pwd = "";
        // 判断密码是否已md5
        if (this.loginInfo.password.indexOf("SHA256_") > -1) {
          md5pwd = this.loginInfo.password;
        } else {
          md5pwd = MD5(this.loginInfo.password).toUpperCase();
          md5pwd = "SHA256_" + md5pwd;
        }
        setCookies("userName", this.loginInfo.userName);
        setCookies("userPass", md5pwd);
        // setCookies("userRole", this.loginInfo.userRole);
        setCookies("identityProvider", this.loginInfo.identityProvider);
      } else {
        removeCookies("userName");
        removeCookies("userPass");
        removeCookies("userRole");
        removeCookies("identityProvider");
      }
    },
    async getTenantList() {
      const {data} =  await TenantApi.listByDomainName({domainName:location.host.split(":")[0]})
      this.tenantList = data||[]
      if(this.tenantList.length<=1){
        this.loginInfo.tenantId = this.tenantList[0].value
      }else{
        this.showTenant = true
      }
    },
    // 加密
    /*encryption(val) {
      const encryptKey = CryptoJS.enc.Latin1.parse("changsha-kanglai");
      const iv = encryptKey;
      return CryptoJS.AES.encrypt(val, encryptKey, {
        iv: iv,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding
      }).toString();
    },*/
    async submitForm() {
      if (!this.loginInfo.userName) {
        this.$message({
          message: "请输入用户名",
          type: "error"
        });
        return;
      }
      if (!this.loginInfo.password) {
        this.$message({
          message: "请输入密码",
          type: "error"
        });
        return;
      }
      const params = {
        userRole: this.loginInfo.userRole,
        userName: this.loginInfo.userName,
        password: this.loginInfo.password,
        tenantId: this.loginInfo.tenantId||'1510456530575347712'
      };

      /*try{
        const {access_token} = await LoginApi.login(params)
        // const user = data.data;
        console.log(access_token,"token")
        setToken(access_token);
        store.commit("SET_TOKEN", getToken());
        // this.$router.push("/");
      }catch(err){
        let { msg } = err.response.data;
        if (msg === "Network Error") {
          msg = "服务器连接异常";
        } else if (msg.includes("credentials")) {
          msg = "用户名或密码错误!";
        } else if (msg.includes("timeout")) {
          msg = "服务器请求超时";
        } else if (msg.includes("Request failed with status code")) {
          msg = "服务器" + msg.substring(msg.length - 3) + "异常";
        }
        this.$message.error(msg || err);
      }*/

      LoginApi.loginByUsername(params).then(res => {
        let data = res.data;
        this.savePwd();
        setStorage("isToken", data.token);
        this.setToken(data.token);
        setStorage(stn.MENU_LIST, data.menuList);
        //setStorage(stn.USER_RELATION, data.userRelation);
        this.$router.push("/");
      });

      /*axios
        .request({
          method: "POST",
          url: `${process.env.AUTH_URL}/oauth/token`,
          headers: {
            Authorization: "Basic a2ljczpraWNz"
          },
          params
        })
        .then(data => {
          const user = data.data;
          setToken(user.access_token);
          store.commit("SET_TOKEN", getToken());
          this.$router.push("/");
        })
        .catch(err => {
          let { msg } = err.response.data;
          if (msg === "Network Error") {
            msg = "服务器连接异常";
          } else if (msg.includes("credentials")) {
            msg = "用户名或密码错误!";
          } else if (msg.includes("timeout")) {
            msg = "服务器请求超时";
          } else if (msg.includes("Request failed with status code")) {
            msg = "服务器" + msg.substring(msg.length - 3) + "异常";
          }
          this.$message.error(msg || err);
        });*/

    }
  },

  created() {
    this.getTenantList();
    let userName = getCookies("userName");
    let userPass = getCookies("userPass");
    let userRole = getCookies("userRole");

    if (userName && userPass && userRole) {
      this.loginInfo.userName = userName;
      this.loginInfo.password = userPass;
      this.loginInfo.userRole = Number(userRole);
      this.loginInfo.isChecked = true;
    } else {
      return;
    }

  },
  mounted() {
    //绑定事件
    window.addEventListener("keydown", this.keyDown);
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  }
};
</script>

<style scope lang="scss" src="../assets/css/components/loginForm.scss"></style>
<style scope lang="scss" src="../../theme/checkbox.css"></style>
